package team.scau.laboratory_repair.web.pc;

import lombok.extern.apachecommons.CommonsLog;
import org.activiti.engine.history.HistoricProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import team.scau.laboratory_repair.common.activiti.dto.RepairProcDto;
import team.scau.laboratory_repair.common.json.PoToDto;
import team.scau.laboratory_repair.common.utils.StringTool;
import team.scau.laboratory_repair.modules.po.Note;
import team.scau.laboratory_repair.service.ActivitiService;
import team.scau.laboratory_repair.common.activiti.dto.ProcDefDto;
import team.scau.laboratory_repair.common.base.BaseController;
import team.scau.laboratory_repair.common.json.JqGridResult;
import team.scau.laboratory_repair.service.AreaService;
import team.scau.laboratory_repair.service.NoteService;
import team.scau.laboratory_repair.service.RecordService;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @author 30254
 * creadtedate:2018/10/14
 */
public class ActivitiController {

    @Controller
    @CommonsLog
    @RequestMapping("/pc/biz/procDef")
    public static class ProcDefController extends BaseController {
        @Autowired
        private ActivitiService activitiService;

        @Autowired
        private PoToDto poToDto;

        @RequiresPermissions("biz:procDef:list")
        @GetMapping(value = "/list", produces = "text/html;charset=utf-8")
        public String list(Model model) throws Exception{
            return "/pc/biz/procDef/list";
        }

        @ResponseBody
        @RequiresPermissions("biz:procDef:list")
        @RequestMapping(value = "/list.json", produces = "application/json;charset=utf-8")
        public JqGridResult list(@RequestParam(value = "name", required = false) String name) throws Exception {
            List<ProcDefDto> list = activitiService.listProcDef(name);
            JqGridResult result = new JqGridResult(list);
            return result;
        }

        @RequiresPermissions("biz:procDef:list")
        @GetMapping(value = "/view", produces = "text/html;charset=utf-8")
        public String view(Model model, @RequestParam("id") String id) throws Exception{
            InputStream in = activitiService.viewProcessDefPng(id);
            OutputStream out = response.getOutputStream();
            for(int b=-1;(b=in.read())!=-1;){
                out.write(b);
            }
            out.close();
            in.close();
            return null;
//            return "/pc/biz/procDef/view";
        }

        @RequiresPermissions("biz:procDef:edit")
        @GetMapping(value = "/edit", produces = "text/html;charset=utf-8")
        public String edit(Model model) throws Exception{
            model.addAttribute("bpmn","");
            model.addAttribute("png","");
            return "/pc/biz/procDef/edit";
        }

        @RequiresPermissions(value = "biz:procDef:edit", logical = Logical.OR)
        @PostMapping(value = "/edit", produces = "application/json;charset=utf-8")
        @ResponseBody
        public Map<String,Object> edit(@RequestParam("name")String name, @RequestParam("key") String key,
                @RequestParam("zip") String zip){
            Map<String,Object> result = new HashMap<>();
            try {
                activitiService.deployProcDef(name, key, zip);
                result.put("status",200);
                result.put("msg","流程部署成功");
            }catch (Exception e){
                e.printStackTrace();
                log.error(e.getMessage(), e);
                result.put("status",500);
                result.put("msg","流程部署失败");
            }
            return result;
        }

        @RequiresPermissions("biz:procDef:delete")
        @PostMapping(value = "/delete", produces = "application/json;charset=utf-8")
        @ResponseBody
        public Map<String,Object> delete(String id){
            Map<String,Object> result = new HashMap<>();
            try {
                if(id != null && !id.isEmpty()){
                    activitiService.deleteProcDef(id);
                    result.put("status",200);
                    result.put("msg","删除流程成功");
                }else {
                    result.put("status",500);
                    result.put("msg","请选择删除的流程");
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error(e.getMessage(), e);
                result.put("status",500);
                result.put("msg","删除流程失败");
            }
            return result;
        }
    }

    @Controller
    @CommonsLog
    @RequestMapping("/pc/biz/procHis")
    public static class ProcHisController extends BaseController {
        @Autowired
        private AreaService areaService;
        @Autowired
        private RecordService recordService;
        @Autowired
        private NoteService noteService;
        @Autowired
        private ActivitiService activitiService;
        @Autowired
        private PoToDto poToDto;

//        @ModelAttribute
//        public HistoricProcessInstance procHis(@RequestParam(required = false, value = "id") String id){
//            if (StringUtils.isNotBlank(id)) {
//                return activitiService.getProcHisById(id);
//            } else {
//                return null;
//            }
//        }

        @RequiresPermissions("biz:procHis:list")
        @GetMapping(value = "/list", produces = "text/html;charset=utf-8")
        public String list(Model model) throws Exception{
            model.addAttribute("curDate", new Date());
            return "/pc/biz/procHis/list";
        }

        @ResponseBody
        @RequiresPermissions("biz:procHis:list")
        @RequestMapping(value = "/list.json", produces = "application/json;charset=utf-8")
        public JqGridResult list(Date after, Date before, String type) throws Exception {
            Boolean finished = null;
            if(type == null) {
                finished = Boolean.FALSE;
            }else if ("end".equals(type)){
                finished = Boolean.TRUE;
            }
            List<HistoricProcessInstance> procs = activitiService.listHistoryProcByIdSetAndDateRangeAndFinished(null, after, before, finished);
            List<RepairProcDto> list = poToDto.repairProcDtoList(procs);
            return new JqGridResult(list);
        }

        @RequiresPermissions("biz:procHis:list")
        @GetMapping(value = "/record", produces = "text/html;charset=utf-8")
        public String record(@RequestParam(required = false, value = "id") String id, Model model) throws Exception{
            Long recordId = 0L;
            if(StringUtils.isNotBlank(id)){
                recordId = activitiService.getProcVar(id, "recordId", Long.class);
            }
            return "redirect:/pc/biz/record/view?id="+recordId;
        }

        @RequiresPermissions("biz:procHis:list")
        @GetMapping(value = "/notes", produces = "text/html;charset=utf-8")
        public String notes(@RequestParam(required = false, value = "id") String id, Model model) throws Exception{
            String notes = "";
            if(StringUtils.isNotBlank(id)){
                notes = activitiService.getProcVar(id, "notes", String.class);
            }
            List<Note> noteList;
            if(StringUtils.isNotBlank(notes)){
                List<Long> longs = StringTool.strings2LongList(notes);
                noteList = noteService.listByIds(longs);
            }else {
                noteList = new ArrayList<>();
            }
            model.addAttribute("notes", noteList);
            return "/pc/biz/procHis/notes";
        }
    }
}
